{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Before we jump into a project with a full dataset, let's just take a look at how the PyTorch LSTM layer really works in practice by visualizing the outputs. We don't need to instantiate a model to see how the layer works. You can run this on FloydHub with the button below under LSTM_starter.ipynb. (You don’t need to run on a GPU for this portion)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[![Run on FloydHub](https://static.floydhub.com/button/button-small.svg)](https://floydhub.com/run?template=https://github.com/gabrielloye/LSTM_Sentiment-Analysis)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Just like the other kinds of layers, we can instantiate an LSTM layer and provide it with the necessary arguments. The full documentation of the accepted arguments can be found here. In this example, we will only be defining the input dimension, hidden dimension and the number of layers.\n",
    "\n",
    "- Input dimension - represents the size of the input at each time step\n",
    "    - e.g. input of dimension 5 will look like this [1, 3, 8, 2, 3]\n",
    "    \n",
    "    \n",
    "- Hidden dimension - represents the size of the hidden state and cell state at each time step\n",
    "    - e.g. the hidden state and cell state will both have the shape of [3, 5, 4] if the hidden dimension is 3\n",
    "    \n",
    "    \n",
    "- Number of layers - the number of LSTM layers stacked on top of each other"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "input_dim = 5\n",
    "hidden_dim = 10\n",
    "n_layers = 1\n",
    "\n",
    "lstm_layer = nn.LSTM(input_dim, hidden_dim, n_layers, batch_first=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's create some dummy data to see how the layer takes in the input. As our input dimension is 5, we have to create a tensor of the shape (1, 1, 5) which represents (*batch size, sequence length, input dimension*). \n",
    "\n",
    "Additionally, we'll have to initialize a hidden state and cell state for the LSTM as this is the first cell. The hidden state and cell state is stored in a tuple with the format (*hidden_state, cell_state*)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Input shape: torch.Size([1, 1, 5])\n",
      "Hidden shape: (torch.Size([1, 1, 10]), torch.Size([1, 1, 10]))\n"
     ]
    }
   ],
   "source": [
    "batch_size = 1\n",
    "seq_len = 1\n",
    "\n",
    "inp = torch.randn(batch_size, seq_len, input_dim)\n",
    "hidden_state = torch.randn(n_layers, batch_size, hidden_dim)\n",
    "cell_state = torch.randn(n_layers, batch_size, hidden_dim)\n",
    "hidden = (hidden_state, cell_state)\n",
    "print(\"Input shape: {}\".format(inp.shape))\n",
    "print(\"Hidden shape: ({}, {})\".format(hidden[0].shape, hidden[1].shape))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we’ll feed the input and hidden states and see what we’ll get back from it"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Output shape:  torch.Size([1, 1, 10])\n",
      "Hidden:  (tensor([[[ 0.0404,  0.0708,  0.2593,  0.2856, -0.3815,  0.2377, -0.2104,\n",
      "           0.0915, -0.1828,  0.3084]]], grad_fn=<StackBackward>), tensor([[[ 0.1387,  0.1333,  0.8220,  1.5785, -0.7639,  0.7654, -1.0385,\n",
      "           0.2465, -0.3239,  0.9978]]], grad_fn=<StackBackward>))\n"
     ]
    }
   ],
   "source": [
    "out, hidden = lstm_layer(inp, hidden)\n",
    "print(\"Output shape: \", out.shape)\n",
    "print(\"Hidden: \", hidden)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the process above, we saw how the LSTM cell will process the input and hidden states at each time step. However in most cases, we'll be processing the input data in large sequences. The LSTM can also take in sequences of variable length and produce an output at each time step. Let's try changing the sequence length this time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "torch.Size([1, 3, 10])\n"
     ]
    }
   ],
   "source": [
    "seq_len = 3\n",
    "inp = torch.randn(batch_size, seq_len, input_dim)\n",
    "out, hidden = lstm_layer(inp, hidden)\n",
    "print(out.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This time, the output's 2nd dimension is 3, indicating that there were 3 outputs given by the LSTM. This corresponds to the length of our input sequence. For the use cases where we'll need an output at every time step, such as Text Generation, the output of each time step can be extracted directly from the 2nd dimension and fed into a fully connected layer. For text classification tasks, such as Sentiment Analysis, the last output can be taken to be fed into a classifier."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "torch.Size([10])\n"
     ]
    }
   ],
   "source": [
    "# Obtaining the last output in the sequence\n",
    "out = out.squeeze()[-1, :]\n",
    "print(out.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "LSTM Cell Equations\n",
    "======"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Input Gate\n",
    "------\n",
    "$i_1 = \\sigma(W_{i_1} \\cdot (H_{t-1}, x_t) + bias_{i_1})$\n",
    "\n",
    "$i_2 = tanh(W_{i_2} \\cdot (H_{t-1}, x_t) + bias_{i_2})$\n",
    "\n",
    "$i_{input} = i_1 * i_2$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Forget Gate\n",
    "------\n",
    "$f = \\sigma(W_{forget} \\cdot (H_{t-1}, x_t) + bias_{forget})$\n",
    "\n",
    "$C_t = C_{t-1} * f + i_{input}$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Output Gate\n",
    "------\n",
    "$O_1 = \\sigma (W_{output_1} \\cdot (H_{t-1}, x_t) + bias_{output_1})$\n",
    "\n",
    "$O_2 = tanh(W_{output_2} \\cdot C_t + bias_{output_2})$\n",
    "\n",
    "$H_t , O_t = O_1 * O_2$"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
